var express = require('express');
var path = require('path');
const { callbackify } = require('util');
var router = express.Router();
var sqlite3 = require('sqlite3').verbose();
var svgCaptcha = require("svg-captcha")
var session = require('express-session')

/* GET users listing. */
// 访问login路由时需要先在req的session中保持用户的信息
router.get('/', function(req, res, next) {  
  console.log("req.query.captcha:",req.query.captcha);
  const captcha = req.query.captcha.toLowerCase();  //验证码，转小写
  var db=new sqlite3.Database(path.join(__dirname, "../db/ChangR.s3db"));  //_dirname="D:\checkin\routes
  var user={
    username:req.query.username,
    password:req.query.password
  };
  req.session.user=user;
  console.log('/GDlogin',user.username,user.password,req.session,req.session.user);
  if(req.session.user){
    // 可以对用户名/密码格式进行检查, 如果非法, 返回提示信息
    if(captcha!==req.session.captcha) {
      return res.send('0');
    }
    // 验证通过，删除保存的验证码
  delete req.session.captcha;
try{
    db.serialize(function() {
      //sqlStr = "CREATE TABLE IF NOT EXISTS TBL_meta (ID varchar2(255), label varchar2(255))"
      sqlStr = "SELECT * FROM `GD_user` ";
      db.all(sqlStr, function(err, rows) {   //查询所有数据
          if(req.query.username == 'rows[1]' )console.log('the result is:',rows[0]);
         var q=0;
         var i=0;
         console.log("rows",rows);
          while(rows[i]){
            if(user.username==rows[i].username&&user.password==rows[i].password){
              q=1;
              console.log("biubiu1");
              break;
            }
            else if(user.username==rows[i].username||user.password==rows[i].password){
              q=2;
              console.log("biubiu2");
              break;
            }
            i=i+1;
          }
          if(q==1){
            req.session.user=user;
            return res.send('1');
          }
          else if(q==2){
            delete req.session.user;
            return res.send('2');
          }
          else if(q==0){
            delete req.session.user;
            return res.send('3');
          }
      });
      db.close();
    });
  }catch(ex){
    console.log(ex);
  }
  }else{
    res.send('4');
  }
});
module.exports = router;
